package org.nod.atgm.gameobjects;

import com.threed.jpct.Object3D;
import com.threed.jpct.SimpleVector;

public class GeometryUtil {
	public static Object3D createPlane(float bottom, float width, float height, SimpleVector direction) {
		Object3D plane = new Object3D(2);
		direction = direction.normalize();

		float x1 = direction.z * width / 2;
		float z1 = -direction.x * width / 2;
		
		float x2 = -direction.z * width / 2;
		float z2 = direction.x * width / 2;
		
		float top = bottom - height;
		
		SimpleVector upperLeftFront=new SimpleVector(x1,top,z1);
	    SimpleVector upperRightFront=new SimpleVector(x2,top,z2);
	    SimpleVector lowerLeftFront=new SimpleVector(x1,bottom,z1);
	    SimpleVector lowerRightFront=new SimpleVector(x2,bottom,z2);
	    
  
	    // Front
	    plane.addTriangle(upperLeftFront,0,0, lowerLeftFront,0,1, upperRightFront,1,0);
	    plane.addTriangle(upperRightFront,1,0, lowerLeftFront,0,1, lowerRightFront,1,1);
		return plane;
	}
	
	public static Object3D[] createCircularRandomPolygons(SimpleVector center, float minDistance, float maxDistance, int count, float polyBottom, float polyWidth, float polyHeight) {
		Object3D[] result = new Object3D[count];
		SimpleVector[] centers = generateCircularRandomPoints(center,minDistance,maxDistance, count);
		SimpleVector direction = new SimpleVector();
		for (int i = 0; i < result.length; i++) {
			direction.x = center.x - centers[i].x;
			direction.z = center.z - centers[i].z;
			result[i] = createPlane(polyBottom,polyWidth,polyHeight,direction);
			result[i].translate(centers[i]);
		}
		return result;
	}
	
	/**
	 * Generates n random points around given center with y == 0;
	 * @param center Center
	 * @param minDistance Min dist to generated point
	 * @param maxDistance Max dist to generated point
	 * @param count point count
	 * @return {@link SimpleVector} array for new points
	 */
	public static SimpleVector[] generateCircularRandomPoints(SimpleVector center, float minDistance, float maxDistance, int count) {
		SimpleVector[] result = new SimpleVector[count];
		float initialZ = 0;
		float delta = maxDistance - minDistance;
		for (int i = 0; i < result.length; i++) {
			float initialX = (float) (Math.random() * delta + minDistance);
			double angle = Math.random() * 2 * Math.PI;
			double cos = Math.cos(angle);
			double sin = Math.sin(angle);
			float x = (float) (initialX * cos - initialZ * sin);
			float z = (float) (initialX * sin + initialZ * cos);
			result[i] = new SimpleVector(x + center.x,0,z + center.z);
		}
		return result;
	}
}
